<template>
  <view class="region">
    <view class="region_left" :style="'width:' + navWidth +'rpx;height: 100%;'">
      <scroll-view :scroll-top="LeftScrollTop" scroll-y="true" class="Leftscroll-Y" :scroll-into-view="leftViewId">
        <view :class="navNowCode == 0 ? 'navDefault navActive' : 'navDefault'" @click="navClick('none')">
          推荐
        </view>
        <view
          v-for="(item,index) in ProvinceList"
          :id="'City' + item.provinceCode"
          :key="index"
          :class="navNowCode == item.provinceCode ? 'navDefault navActive' : 'navDefault'"
          @click="navClick(item, index + 1)"
        >
          {{ item.provinceName }}
        </view>
      </scroll-view>
    </view>
    <scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" :scroll-into-view="viewId">
      <view class="scrollContent">
        <view id="City100" class="grouping">
          <view class="cityName">当前定位</view>
          <view class="Citylist">
            <view v-if="!!Address" class="activeCity" @click="chioseRegion('map')">
              <u-icon name="map" color="#FF5533" size="20" />
              {{ Address }}
            </view>
            <view v-else class="activeCity" style="color: #E51728" @click="reloadAddress">
              <u-icon name="reload" color="#E51728" size="20" />
              定位失败 请重新获取
            </view>
          </view>
        </view>
        <!--热门城市-->
        <view class="grouping">
          <view class="cityName">热门</view>
          <view class="Citylist">
            <view
              v-for="(item, index) in hotCityList"
              :key="index"
              :class="item.dictValue.code == HotcityCode ? 'activeCity' : ''"
              @click="chioseHotRegion(item)"
            >
              {{ item.dictLabel }}
            </view>
          </view>
        </view>
        <!--二级城市-->
        <view v-for="(item, index) in CityList" :id="'City' + item.provinceCode" :key="index" class="grouping">
          <view class="cityName">{{ item.provinceName }}</view>
          <view class="Citylist">
            <view
              v-for="(result, resultIndex) in item.childList"
              :key="resultIndex"
              :class="result.code == cityCode ? 'activeCity' : ''"
              @click="chioseRegion(result, index)"
            >{{ result.name }}
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view v-if="showRegion" class="regionChioce">
      <TopTabs
        class="getTop"
        :list-data="allCityList"
        key-name="name"
        :current.sync="current"
        :inactive-style="inactiveStyle"
        :active-style="activeStyle"
        :line-color-obj="lineColorObj"
        :border-bom="true"
        @tabClick="tabClick"
      />
      <view v-for="(item, index) in thressCityList" v-if="current == 2" :key="index" class="chioseRe">
        <view class="title">{{ item.pinyinPrefix }}</view>
        <view v-for="(result, resultIndex) in item.firstLetterAddressList" :key="resultIndex" class="content" @click="cityChoice(result)">
          <view :class="threeCode == result.code ? 'radioDefault radioAcitve' : 'radioDefault'">
            <u-icon v-if="threeCode == result.code" name="checkmark" color="#FFFFFF" size="10" />
          </view>
          {{ result.name }}
        </view>
      </view>
      <view v-for="(item, index) in fourCityList" v-if="current == 3" :key="index" class="chioseRe">
        <view class="title">{{ item.pinyinPrefix }}</view>
        <view v-for="(result, resultIndex) in item.firstLetterAddressList" :key="resultIndex" class="content" @click="fourCityChoice(result)">
          <view :class="FourCode == result.code ? 'radioDefault radioAcitve' : 'radioDefault'">
            <u-icon v-if="FourCode == result.code" name="checkmark" color="#FFFFFF" size="10" />
          </view>
          {{ result.name }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TopTabs from '@/components/top-tabs';
import { getHotCity, getCity, getAddress, getDiffCity, getThreeCity, getWare } from '@/api/commonApi.js'

export default {
  components: {
    TopTabs
  },
  props: {
    navWidth: {
      type: Number,
      default: 156
    },
    saveFlag: { // 选择城市后是否保存到本地
      type: Boolean,
      default: false
    },
    allCity: { // 是否显示所有地址
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      navNowCode: 0,
      hotCityList: [], // 热门城市
      CityList: [], // 城市列表
      ProvinceList: [], // 省级城市
      height: 0,
      inactiveStyle: {
        fontSize: '28rpx'
      },
      activeStyle: {
        fontSize: '28rpx',
        transform: 'scale(1)',
        fontWeight: ''
      },
      lineColorObj: {
        width: '60',
        bgUrl: `#FF6010`,
        height: '3',
        bottom: '0'
      },
      allCityList: [],
      showRegion: false,
      LeftScrollTop: 0,
      scrollTop: 0,
      Address: '',
      cityCode: '',
      diffCityList: [],
      viewId: '',
      leftViewId: '',
      HotcityCode: '',
      mapAddress: {}, //当前定位信息
      cityArr: ['110000', '120000', '310000', '500000'], // 需要过滤直辖市
      thressCityList: [],
      threeCode: '',
      FourCode: '',
      current: 2,
      fourCityList: []
    }
  },
  mounted() {
    this.height = uni.getSystemInfoSync().windowHeight
    this.getCity()
    this.getLocation() // 待确定是否每次进入都需要重新调用
  },
  methods: {
    // 初次获取定位
    getLocation() {
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.getAddress(res.latitude, res.longitude) // 经纬度获取定位信息
        },
        fail: () => {
          // this.$u.toast({ title: '获取位置信息失败', icon: 'none' });
          // this.Address = ''
        }
      });
    },
    // 再次唤起授权弹框、模拟弹框直接调用设置
    openAuthSetting() {
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
            uni.showModal({
              title: '请求授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: (res) => {
                if (res.cancel) {
                  this.$u.toast('拒绝授权');
                } else if (res.confirm) {
                  uni.openSetting({
                    success: (dataAu) => {
                      if (dataAu.authSetting['scope.userLocation'] == true) {
                        this.$u.toast('授权成功');
                        //再次授权，调用wx.getLocation的API
                        this.getLocation();
                      } else {
                        this.$u.toast('获取位置信息失败');
                      }
                    },
                  });
                }
              },
            });
          } else if (res.authSetting['scope.userLocation'] == undefined) {
            //调用wx.getLocation的API
            this.getLocation();
          } else {
            //调用wx.getLocation的API
            this.getLocation();
          }
        },
        complete() {
          // console.log('getSetting');
        },
      });
    },
    reloadAddress() { // 刷新定位
      this.openAuthSetting()
    },
    getDiffCity(districtName, cityName) { // 获取特殊城市
      const params = { type: 10 }
      getDiffCity(params).then((res) => {
        if (res.errorCode == 0) {
          this.diffCityList = res.data
          // 特殊城市展示三级、不是特殊城市展示二级
          this.Address = res.data.includes(cityName) ? districtName : cityName
        }
      })
    },
    getAddress(lat, lng) { // 获取地址信息
      const params = { lat, lng }
      getAddress(params).then((res) => {
        this.mapAddress = res.data
        uni.$u.vuex('vuex_mapAddress', res.data);
        const { districtName, cityName } = res.data
        if (res.errorCode == 0) {
          this.getDiffCity(districtName, cityName)
        }
      })
    },
    getHotCity() { // 获取热门城市
      const params = { dictType: 'HOT_CITY_LIST' }
      getHotCity(params).then((res) => {
        if (res.errorCode == 0) {
          this.hotCityList = res.data.dictDataList.map((item) => {
            return { ...item, dictValue: JSON.parse(item.dictValue) }
          })
        }
      })
    },
    getCity() { // 获取城市
      getCity().then((res) => {
        if (res.errorCode == 0) {
          this.CityList = res.data.filter((item) => !this.cityArr.includes(item.provinceCode))
          this.ProvinceList = res.data.map((item) => {
            if (item.provinceName.includes('内蒙古')) {
              item.provinceName = '内蒙古'
            } else if (item.provinceName.includes('广西')) {
              item.provinceName = '广西省'
            } else if (item.provinceName.includes('西藏')) {
              item.provinceName = '西藏'
            } else if (item.provinceName.includes('宁夏')) {
              item.provinceName = '宁夏省'
            } else if (item.provinceName.includes('新疆')) {
              item.provinceName = '新疆'
            }
            return item
          })
          this.getHotCity(res.data)
        }
      })
    },
    getThreeCity(code, typeNum = '') { // 获取特殊城市三级数据
      const params = { code }
      getThreeCity(params).then((res) => {
        if (res.errorCode == 0 && typeNum !== 'four') {
          this.thressCityList = res.data
        } else {
          this.fourCityList = res.data
        }
      })
    },
    navClick(item, index) { // 左边导航栏点击
      if (item == 'none') {
        this.navNowCode = 0
        this.viewId = 'City100'
      } else if (this.cityArr.includes(item.provinceCode)) {
        this.viewId = 'City100'
        this.navNowCode = item.provinceCode
      } else {
        this.viewId = 'City' + item.provinceCode
        this.navNowCode = item.provinceCode
      }
    },
    chioseRegion(item) { // 二级城市点击
      this.navNowCode = item.parent_code
      this.cityCode = item.code
      this.HotcityCode = ''
      this.leftViewId = 'City' + item.parent_code
      if (item !== 'map') {
        var parent = this.ProvinceList.filter((result) => result.provinceCode == item.parent_code)
        this.allCityList = [
          { name: parent[0].provinceName, keyName: parent[0].provinceCode, id: parent[0].address_id },
          { name: item.name, keyName: item.code, id: item.address_id },
          { name: '请选择', keyName: '' }
        ]
        if (this.diffCityList.includes(item.name) || this.allCity) { // 判断当存在三级时，显示三级选择项，调用接口
          this.showRegion = true
          this.getThreeCity(item.code)
        } else { // 不存在则直接抛出当前点击二级信息
          this.getWare(item.name, 102)
        }
      } else { // TODO 当不为map时，为点击当前位置。
        const { cityId, cityName, cityCode, provinceId, provinceName, provinceCode } = this.mapAddress
        this.allCityList = [
          { name: provinceName, keyName: provinceCode, id: provinceId },
          { name: cityName, keyName: cityCode, id: cityId },
          { name: '请选择', keyName: '' }
        ]
        if (this.diffCityList.includes(cityName) || this.allCity) { //如果是特殊城市,使用二级code请求三级数据
          this.showRegion = true
          this.getThreeCity(cityCode)
        } else { // 当不存在三级时， 直接调用接口查找此二级数据并抛出
          this.getWare(cityName, 102)
        }
      }
    },
    chioseHotRegion(item) { // 热门城市点击，TODO 直接调用getWare 传102+ 当前点击城市的name=
      this.navNowCode = item.dictValue.parent_code
      var parent = this.ProvinceList.filter((result) => result.provinceCode == item.dictValue.parent_code)
      this.allCityList = [
        { name: parent[0].provinceName, keyName: parent[0].provinceCode, id: parent[0].address_id },
        { name: item.dictValue.name, keyName: item.dictValue.code, id: item.dictValue.address_id },
        { name: '请选择', keyName: '' }
      ]
      this.cityCode = ''
      this.HotcityCode = item.dictValue.code
      this.leftViewId = 'City' + item.dictValue.parent_code
      if (this.diffCityList.includes(item.name) || this.allCity) {
        this.showRegion = true
        this.getThreeCity(item.dictValue.code)
      } else {
        this.getWare(item.dictLabel, 102)
      }
    },
    cityChoice(item) { // 三级城市点击
      this.threeCode = item.code
      this.current = 3
      this.allCityList[2] = { name: item.name, keyName: item.code, id: item.address_id }// 当三级城市选中时，需要调用接口查找仓
      if (this.allCity) {
        const params = { code: item.code }
        getThreeCity(params).then((res) => {
          if (res.errorCode == 0 && res.data.length > 0) {
            this.allCityList[3] = { name: '请选择', keyName: '' }
            this.fourCityList = res.data
          } else {
            this.allCityList[3] = { name: '', keyName: '' }
            this.$emit('getParams', this.allCityList)
          }
        })
        // this.allCityList[3] = { name: '请选择', keyName: '' }
        // this.getThreeCity(item.code, 'four')
      } else {
        this.getWare(item.name, item.level)
      }
    },
    fourCityChoice(item) {
      this.FourCode = item.code
      this.allCityList[3] = { name: item.name, keyName: item.code, id: item.address_id }
      this.$emit('getParams', this.allCityList)
    },
    getWare(name, level) {
      const params = { name, level }
      getWare(params).then((res) => {
        if (res.errorCode == 0) {
          var cityParams = {}
          const { grandpa_code, grandpa_name, parent_name, parent_code, name, code, warehouse_code, level } = res.data
          if (level == 102) {
            cityParams = {
              provinceCode: parent_code,
              provinceName: parent_name,
              cityCode: code,
              cityName: name,
              areaCode: '',
              areaName: '',
              warehouseCode: warehouse_code
            }
          } else if (level == 103) {
            cityParams = {
              provinceCode: grandpa_code,
              provinceName: grandpa_name,
              cityCode: parent_code,
              cityName: parent_name,
              areaCode: code,
              areaName: name,
              warehouseCode: warehouse_code
            }
          }
          if (this.saveFlag) {
            uni.$u.vuex('vuex_nowAddress', res.data);
            uni.$u.vuex('vuex_cityInfo', cityParams);
            // #ifdef H5
            this.$cookie.set('cityCode', cityParams.cityCode)
            this.$cookie.set('warehouseCode', cityParams.warehouseCode)
            this.$cookie.set('provinceCode', cityParams.provinceCode)
            localStorage.setItem('my_select_station', JSON.stringify(cityParams));
            // #endif
            uni.$u.vuex('vuex_cityInfo_shopCar', {});
            uni.$u.vuex('vuex_cityInfo_shopCarClick', false);
            this.$emit('getParams', res.data, cityParams)
          } else {
            this.$emit('getParams', res.data, cityParams)
          }
        }
      })
    },
    tabClick(e) { // 三级顶部标签点击
      if (e.index < 2) {
        this.current = 2
        this.showRegion = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.activeCity {
  color: #FF5533;
  display: flex;
  justify-content: space-around;
  align-content: center;
  align-items: center;
  /deep/ .u-icon--right {
    margin-right: 5rpx !important;
    /* #ifdef H5 */
    height:14rpx;
  /* #endif */
  }
  /deep/ .u-icon--right .u-icon__icon.uicon-reload {
    /* #ifdef H5 */
    margin-top: -14rpx;
  /* #endif */
  }
  /deep/ .u-icon--right .u-icon__icon.uicon-map {
    /* #ifdef H5 */
    margin-top: -14rpx;
  /* #endif */
  }
}
.indes {
  width: 100%;
  height: 100rpx;
  background: #666666;
}
.region_left {
  flex-shrink: 0;
  .Leftscroll-Y {
    box-sizing: border-box;
    height: 100%;
  }
}
.swiper-item{
  height: 88rpx!important;
}
.navDefault{
  height: 88rpx;
  line-height: 88rpx;
  font-size: 28rpx;
  background-color: #fff;
  color: #222222;
  padding: 0 16rpx;
  text-align: center;
  box-sizing: border-box;
}
.navActive{
  background: #F5F5F5 !important;
  color: #FF5533;
  position: relative;
}
.navActive:after{
  position: absolute;
  left: 0;
  top: 24rpx;
  width: 8rpx;
  height: 40rpx;
  border-radius: 0 4rpx 4rpx 0;
  background: #FF5533;
  content: ' ';
}
/deep/ .u-tabs__wrapper__nav__line {
  bottom: 0 !important;
}
.chioseRe {
  margin-top: 48rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  .title {
    margin-bottom: 8rpx;
    font-weight: bold;
    border-bottom: 1rpx solid rgba(245,245,245,1);
    padding: 0rpx 32rpx;
    box-sizing: border-box;
    padding-bottom: 5rpx;
  }
  .content {
    display: flex;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    padding: 0rpx 32rpx;
    color: #222222;
    box-sizing: border-box;
    margin-top: 28rpx;
  }
  .radioDefault {
    flex-shrink: 0;
    width: 32rpx;
    height: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    border-radius: 50%;
    border: 1rpx solid #D3D3D3;
    margin-right: 16rpx;
  }
  .radioAcitve {
    background: #FF5533;
  }
}
.chioseRe:nth-of-type(1) {
  margin-top: 122rpx;
}
.region {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  position: relative;
}
.scroll-Y {
  width: 100%;
  background: #F5F5F5;
  height: 100%;
  .scrollContent {
    padding: 0 32rpx 32rpx 32rpx;
    box-sizing: border-box;
  }
}
.grouping {
  width: 100%;
  padding-top: 32rpx;
  box-sizing: border-box;
  .cityName {
    color: rgba(0,0,0,1);
    font-size: 28rpx;
    font-weight: 600;
  }
}
.Citylist {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  view {
    height: 72rpx;
    padding: 0 30rpx;
    background: #fff;
    border-radius: 8rpx;
    box-sizing: border-box;
    margin-top: 16rpx;
    margin-right: 16rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 28rpx;
  }
}
.regionChioce {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #FFFFFF;
  z-index: 2;
  padding: 0rpx 0rpx 68rpx 0rpx;
  box-sizing: border-box;
  overflow-y: auto;
}

</style>
